<?php
/**
 * 管理员类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Admin extends Base{
    protected function _initialize(){
        if (in_array($this->request->action(),['adminshow','portraitupload','setpassword'])) {  //字母小写
            $this->needAuth  = false;  // 关闭权限验证
        }
        parent::_initialize();
    }

    /**
     * 列表
     * @return \Illuminate\View\View|string|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminList(){
        if (IS_AJAX && IS_POST) {
            $search = search($this->params, ['a.id','a.username']);
            $where  = $search['where'] ? $search['where'].' and ' : '';
            $where .= 'a.id > '.\Param::GROUP_ADMIN.' and a.status in ('.\Param::STATUS_ON.', '.\Param::STATUS_OFF.')';
            $order  = sort_list($this->params);
            $list   = $this->admin
                ->alias('a')
                ->field('a.*,c.pid,c.id as group_id,c.group_name,d.group_name as p_group')
                ->join([['auth_group_access b','a.id = b.uid','left'],['auth_group c','b.group_id = c.id','left'],['auth_group d','c.pid = d.id','left']])
                ->where($where)
                ->order($order ?: ['id'=>'desc'])
                ->select();
            foreach ($list as $k=>&$v) {
                $v['last_login_ip']  = long2ip($v['last_login_ip']);
                $v['selected_group'] = [$v['group_id']];
                if ($v['pid'] > 0) {
                    $v['group_name'] = $v['p_group'].' / '.$v['group_name'];
                    $v['selected_group'] = [$v['pid'], $v['group_id']];
                }
            }
            return success($list);
        }
        return view('adminList');
    }

    /**
     * 格式化用户组列表
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function groupList(){
        $list = $this->getList(
            $this->auth_group,
            ['id'=>['>',\Param::GROUP_ADMIN],'status'=>\Param::STATUS_ON],
            'id,pid,group_name',
            'pid asc'
        );

        $plist = [];
        foreach ($list as $k=>$v) {
            if ($v['pid'] == 0) {
                $plist[$k]['value'] = $v['id'];
                $plist[$k]['label'] = $v['group_name'];
                continue;
            }
            if ($plist) {
                foreach ($plist as $k1=>&$v1) {
                    if ($v['pid'] == $v1['value']) {
                        $v1['children'][] = ['value'=>$v['id'],'label'=>$v['group_name']];
                    }
                }
            }
        }
        sort($plist);
        return success($plist);
    }

    /**
     * 拖动排序
     * @return string
     */
    public function sort(){
        if (IS_POST) {
            try {
                $list = $this->admin
                    ->field('id,sort')
                    ->where(['id'=>['in',$this->params['id']]])
                    ->select();

                if (empty($list) || count($list) != 2) {
                    throw new \Exception('排序不存在', -1);
                }

                $sort = array_column($list, 'sort');
                $list[0]['sort'] = $sort[1];
                $list[1]['sort'] = $sort[0];

                $where = "id IN ({$this->params['id']})";
                $res = $this->updateBatch($list, 'it_admin', 'sort', 'id', $where);
                if (!$res) {
                    throw new \Exception('操作失败', -1);
                }
                $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "修改“ID：{$this->params['id']}”管理员排序"];
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
    }

    /**
     * 操作
     * @return array|\think\response\View
     */
    public function adminSave(){
        if(IS_POST){
            try{
                if (!empty($this->params['id'])) {
                    //todo 更新
                    $group_info = $this->getRow($this->auth_group, $this->params['group_id']);

                    $row = $this->auth_group_access->where(['uid'=>$this->params['id']])->update(['group_id'=>$this->params['group_id']]);
                    if (false === $row) throw new \Exception('操作失败', -1);

                    $row = $this->admin->where(['id'=>$this->params['id']])->update(['update_time'=>time()]);
                    if (false === $row) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "修改“ID：{$this->params['id']}”管理员“{$this->params['username']}”，用户组为“{$group_info['group_name']}”"];
                } else {
                    //todo 添加
                    $validate = self::validate($this->params, 'Admin.adminAdd');  // 场景验证
                    if(true !== $validate) throw new \Exception($validate, -1);

                    $add = [
                        'username'    => $this->params['username'],
                        'password'    => password_hash($this->params['password'],true),
                        'create_time' => time()
                    ];
                    $uid = $this->admin->insertGetId($add);  // 添加管理员
                    $aid = $this->auth_group_access->insert(['uid'=>$uid, 'group_id'=>$this->params['group_id']]);  // 关系表添加记录
                    if (!$uid || false === $aid) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['新增管理员', \Param::LOG_TYPE_ADD, "新增“ID：{$uid}”管理员“{$this->params['username']}”"];
                }
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
    }

    /**
     * 修改密码
     * @return array|\think\response\View
     */
    public function setPassword(){
        if(IS_POST){
            try{
                $info = $this->getRow($this->admin, $this->params['id']);
                if (!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该用户不存在', -1);

                $check = password_verify($this->params['oldpassword'], $info['password']);
                if (!$check) throw new \Exception('密码错误', -1);

                $password = password_hash($this->params['password'], true);
                $row = $this->admin->update(['id'=>$this->params['id'],'password'=>$password,'update_time'=>time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $this->logs[] = ['修改密码', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”管理员“{$info['username']}”密码"];
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
        return view('setPassword');
    }

    /**
     * 重置密码
     * 密码为123456
     * @throws \Exception
     */
    public function resetPassword(){
        if(IS_POST) {
            try {
                $info = $this->getRow($this->admin, $this->params['id']);
                if (!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该用户不存在', -1);

                $password = password_hash('123456', true);
                $row = $this->admin->update(['id' => $this->params['id'], 'password' => $password, 'update_time' => time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $this->logs[] = ['修改密码', \Param::LOG_TYPE_EDIT, "重置“ID：{$info['id']}”管理员“{$info['username']}”密码"];
            } catch (\Exception $e) {
                return error($e->getCode(), $e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
    }

    /**
     * 修改状态
     * @return array
     */
    public function status(){
        if(IS_POST){
            try{
                $info = $this->getRow($this->admin, $this->params['id']);
                if( !$info || $info['status'] == \Param::STATUS_DEL ) throw new \Exception('该用户不存在', -1);

                $row = $this->admin->update(['id'=>$this->params['id'],'status'=>$this->params['status'],'update_time'=>time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $status = $this->params['status'] == \Param::STATUS_ON ? '已启用' : '已禁用';

                $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”管理员“{$info['username']}”状态为“{$status}”"];
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
    }

    /**
     * 软删除
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function del(){
        if(IS_POST) {
            try {
                $info = $this->getRow($this->admin, $this->params['id']);
                if (!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该用户不存在', -1);

                $row = $this->admin->update(['id' => $this->params['id'], 'status' => \Param::STATUS_DEL, 'update_time' => time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”管理员“{$info['username']}”状态为“已删除”"];
            } catch (\Exception $e) {
                return error($e->getCode(), $e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
    }

    /**
     * 详情
     * @return string|\think\response\Json|\think\response\View
     */
    public function ucenter(){
        if (IS_AJAX && IS_POST) {
            //获取用户信息
            $info = $this->info;

            $data = [
                'info' => $info
            ];
            return success($data);
        }


        // 获取日志列表
//        $list = $this->admin_log
//            ->where(['uid'=>$this->id])
//            ->order('id desc')
//            ->paginate(10, false, ['query'=>$this->params, 'var_page'=>'page']);
//
//        $group = [];
//        $admin = [];
//        if ($info['pid'] == 0) {
//            // 获取下级用户组列表
//            $group_where =
//                $this->id == \Param::GROUP_ADMIN
//                ? ['status'=>['in',[\Param::STATUS_ON,\Param::STATUS_OFF]],'id'=>['>',\Param::GROUP_ADMIN]]
//                : ['pid'=>$info['group_id'],'status'=>['in',[\Param::STATUS_ON,\Param::STATUS_OFF]]];
//            $group = $this->auth_group
//                ->where($group_where)
//                ->select();
//            foreach ($group as $k=>$v) {
//                $rules = $this->getColumn($this->auth_rule, ['id'=>['in',$v['auth_ids']]],'rule_name');
//                $group[$k]['auth_ids'] = implode(',',$rules);
//            }
//            $info['count_group'] = count($group);
//
//
//            // 获取下级用户列表
//            $ids = array_column($group, 'id');
//            $admin_where = $this->id == \Param::GROUP_ADMIN
//                ? ['b.status'=>['neq',\Param::STATUS_DEL],'a.uid'=>['>',\Param::GROUP_ADMIN]]
//                : ['b.status'=>['neq',\Param::STATUS_DEL],'a.uid'=>['in',$ids]];
//            $admin = $this->auth_group_access
//                ->alias('a')
//                ->field('b.*,c.group_name')
//                ->join([['admin b','a.uid = b.id','inner'],['auth_group c','a.group_id = c.id','inner']])
//                ->where($admin_where)
//                ->select();
//            $info['count_admin'] = count($admin);
//        } else {
//            //非顶级用户组，拼接顶级组名
//            $group_name = $this->getValue($this->auth_group, ['id'=>$info['pid']], 'group_name');
//            $info['group_name'] = $info['group_name'].'-'.$group_name;
//        }

//        return view('ucenter',['list'=>$list,'info'=>$info,'group'=>$group,'admin'=>$admin]);
        return view('ucenter');
    }

    /**
     * 上传文件到服务器
     * @return string|\think\response\Json
     */
    public function portraitUpload(){
        if(IS_POST){
            try{
                $file = request()->file('image');
                $file_path = upload($file, $this->params['file_name']);

                $row = $this->admin->update(['id'=>$this->id,'portrait'=>$file_path[0],'update_time'=>time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                cookie('portrait', null);  // 记录头像
                cookie('portrait', $file_path[0]);

                $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "上传“ID：{$this->id}”管理员“{$this->info['username']}”头像"];
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success(['path'=>$file_path[0]]);
        }
    }
}